package com.gzhryc.shared_device.oem.h5.agent.controllers.callback;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.EncryptTools;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.outside.znst.OperateLightResponse;
import com.gzhryc.shared_device.bxscn.code.outside.znst.ZhongNengSiTuoAPIService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.oem.code.device.BXSCNCacheManager;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.callback.OutsideZNSKResultRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.callback.OutsideZNSKResultResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class OutsideZNSKController {

    static Logger log = Logger.getLogger(OutsideZNSKController.class);

    static String token = "2d7612c10ed04be9a7cc0fd19a58e65e";

    @Route(value = "/outside/callback/znsk/active/result")
    public OutsideZNSKResultResponse resultCallback(HttpServletRequest request) {
        OutsideZNSKResultResponse apiResp = new OutsideZNSKResultResponse(ClientAPICodeConstants.EXECUTE_ERROR,"处理失败");
        OutsideZNSKResultRequest apiReq = WebUtils.getForceJsonRequest(request, OutsideZNSKResultRequest.class);
        log.info("中能思拓设备开启关闭回调：{{0:json}}",apiReq);
        if(apiReq != null && StringTools.isNotBlank(apiReq.getDeviceSn()) && StringTools.isNotBlank(apiReq.getTradeNo())
            && StringTools.isNotBlank(apiReq.getSign()) && apiReq.getHour() != null){
            String deviceSn = apiReq.getDeviceSn().replace(" ","");
            deviceSn = deviceSn.replace("-","");

            String content = apiReq.getTradeNo() + deviceSn + apiReq.getHour() + token;
            String sign = EncryptTools.md5(content);
            if(!apiReq.getSign().equals(sign)) {
                log.error("签名错误，暂时忽略");
                apiResp.setMsg("签名错误");
            }

            BXSCNShopOrder shopOrder = BXSCNShopOrderService.self(new Date()).getByTradeNo(apiReq.getTradeNo());
            if(shopOrder != null){
                Integer hour = shopOrder.getLeaseDay() * 24 + 24;      //默认多一天
                if(apiReq.getHour() == 0 || apiReq.getHour().equals(hour)){
                    //缓存命令返回结果
                    BXSCNCacheManager.self().setCommandResult(deviceSn,apiReq.getTradeNo(), JsonTools.toJson(apiReq));
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                }else{
                    log.error("订单信息验证失败，开始时长：" + hour + "，回调时长：" + apiReq.getHour());
                    apiResp.setMsg("订单信息验证失败");
                }
            }else{
                log.error("未找到订单信息，订单信息：{{0}}",apiReq.getTradeNo());
                //缓存命令返回结果
                BXSCNCacheManager.self().setCommandResult(deviceSn,apiReq.getTradeNo(), JsonTools.toJson(apiReq));
                apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            }
            
            if(ClientAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
            	//发送亮灯
            	try {
                    String token = ZhongNengSiTuoAPIService.self().getToken();
                    if (StringTools.isNotBlank(token)) {
                    	OperateLightResponse operateLightResp = ZhongNengSiTuoAPIService.self().sendOperateLignt(token,apiReq.getDeviceSn(),1);
                        if (operateLightResp != null) {
                            if (200 != operateLightResp.getCode()) {
                            	if (StringTools.isNotBlank(operateLightResp.getMsg())) {
                            		log.error("亮灯错误：" + operateLightResp.getMsg());
                            	} else {
                            		log.error("亮灯返回结果解析失败");
                            	}
                            }
                        } else {
                        	log.error("亮灯无响应");
                        }
                    }
                } catch (LogicException e) {
                	log.error(e.getMessage(), e);
                }
            }
        }else {
            log.error("参数缺失");
            apiResp.setMsg("参数缺失");
        }
        return apiResp;
    }
}
